<template>
  <div class="dashboard-container body-min-width">
    <h2 class="head-big-title">Papan Pemuka</h2>
    <div style="width: 92%;margin: 0 4% 20px 4%">
      <el-card shadow="always" :class="{'four-card':role == adminValue,'five-card':!(role == adminValue)}" :body-style="{ padding: '15px 0 25px 20px' }">
        <h2 class="title">Jumlah Pesanan</h2>
        <h2 class="count">{{dashboardData.totalPOs}}</h2>
      </el-card>
      <el-card shadow="always" :class="{'four-card':role == adminValue,'five-card':!(role == adminValue)}" :body-style="{ padding: '15px 0 25px 20px' }">
        <h2 class="title">Jumlah Pesanan Yang Belum Selesai</h2>
        <h2 class="count">{{dashboardData.totalProcessPOs}}</h2>
      </el-card>
      <el-card shadow="always" :class="{'four-card':role == adminValue,'five-card':!(role == adminValue)}" :body-style="{ padding: '15px 0 25px 20px' }">
        <h2 class="title">Jumlah Pesanan Yang Selesai</h2>
        <h2 class="count">{{dashboardData.totalCompletedPos}}</h2>
      </el-card>
      <el-card shadow="always" class="four-card" v-show="role == adminValue" :body-style="{ padding: '15px 0 25px 20px' }">
        <h2 class="title">Jumlah Jualan (MYR)</h2>
        <h2 class="count">{{dashboardData.totalSales}}</h2>
      </el-card>
      <el-card shadow="always" :class="{'four-card':role == adminValue,'five-card':role == agencyValue}" v-show="(role == adminValue)||(role == agencyValue)" :body-style="{ padding: '15px 0 25px 20px' }">
        <h2 class="title">Jumlah Dealer Utama</h2>
        <h2 class="count">{{dashboardData.totalMasterDealers}}</h2>
      </el-card>
      <el-card shadow="always" :class="{'four-card':role == adminValue,'five-card':role == dealerMValue}" v-show="(role == adminValue)||(role == dealerMValue)" :body-style="{ padding: '15px 0 25px 20px' }">
        <h2 class="title">Jumlah Dealer</h2>
        <h2 class="count">{{dashboardData.totalDealers}}</h2>
      </el-card>
      <el-card shadow="always" :class="{'four-card':role == adminValue,'five-card':!(role == adminValue)}" v-show="!(role == dealerValue)" :body-style="{ padding: '15px 0 25px 20px' }">
        <h2 class="title">Jumlah Dealer Yang Menunggu Kelulusan</h2>
        <h2 class="count">{{dashboardData.totalPendingDealer}}</h2>
      </el-card>
    </div>
    <h2 class="big-title">Pesanan Pembelian Melepasi 30 Hari</h2>
    <div class="last-days-order">
      <div id="orderChart" style="width:100%;height:278px;"></div>
    </div>
    <h2 class="big-title">Pesanan Pembelian Terkini</h2>
    <el-table
      :data="orderTableData"
      style="width: 92%;margin: 20px 4% 16px 4%;padding-left: 10px;border-radius: 20px">
      <el-table-column prop="oid" label="Nombor Pesanan" width="180"></el-table-column>
      <el-table-column prop="dealerName" label="Nama Pelanggan" v-if="role !=dealerValue"></el-table-column>
      <el-table-column prop="phoneNumber" label="Nombor Telefon" v-if="role !=dealerValue"></el-table-column>
      <el-table-column label="Tarikh">
        <template slot-scope="scope">
          {{ $getTime(scope.row.createdAt)}}
        </template>
      </el-table-column>
      <el-table-column prop="updateAt" label="Tarikh Penghantaran">
        <template slot-scope="scope">
          {{$getTime(scope.row.updateAt) }}
        </template>
      </el-table-column>
      <el-table-column label="Status">
        <template slot-scope="scope">
          <el-tag type="success" v-for="(item, index) in $orderStateList" :key="index" v-show="scope.row.state == item.value">{{item.label}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="subFee" label="Jumlah">
        <template slot-scope="scope">
          {{ $formatMoneyStr(scope.row.subFee)}}
        </template>
      </el-table-column>
      <el-table-column label="Tindakan" width="166" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            style="font-size: 26px;padding: 0;background-color: rgb(56,96,134);border: 0;margin-left: 18px;"
            @click="handleEditView(scope.row)">
            <svg-icon icon-class="ico_view"></svg-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <h2 class="big-title" v-show="role == agencyValue || role == dealerMValue">Pending Approval Dealers</h2>
    <el-table
      :data="dealerTableData"
      v-show="role == agencyValue || role == dealerMValue"
      style="width: 92%;margin: 20px 4% 15px 4%;padding-left: 10px;border-radius: 20px">
      <el-table-column label="Logo" width="100">
        <template slot-scope="scope">
          <img
            v-if="scope.row.typeCompany"
            style="width: 64px; height: 64px"
            :src="picbase + scope.row.logoUrl"/>
          <img
            v-if="!scope.row.typeCompany"
            style="width: 64px; height: 64px"
            :src="picbase + scope.row.certificateUrl"/>
        </template>
      </el-table-column>
      <el-table-column prop="createAt" label="Tarikh"></el-table-column>
      <el-table-column prop="dealerName" label="Nama Dealer"></el-table-column>
      <el-table-column prop="registCode" label="Nombor Pendaftaran"></el-table-column>
      <el-table-column prop="phoneNumber" label="Nombor Telefon"></el-table-column>
      <el-table-column label="Status">
        <template slot-scope="scope">
          <p>Pending</p>
        </template>
      </el-table-column>
      <el-table-column label="Tindakan" width="166" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            style="font-size: 26px;padding: 0;background-color: rgb(253,181,0);border: 0;margin-right: 18px;"
            @click="handleConfirm(scope.row)">
            <svg-icon icon-class="ico_approve"></svg-icon>
          </el-button>
          <el-button
            type="primary"
            size="mini"
            style="font-size: 26px;padding: 0;background-color: rgb(56,96,134);border: 0;margin-left: 18px;"
            @click="handleEdit(scope.row)">
            <svg-icon icon-class="ico_view"></svg-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  orderRecentApi,
  verifyMdealerApi,
  adminDashboardApi,
  agentDashboardApi,
  masterdealerDashboardApi,
  dealerDashboardApi,
  queryDealerDashboardApi,
  passOwnerDealerApi
} from '@/api/user'
// import router from '@/router'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'role',
      'headUrl',
      'name'
    ])
  },
  data() {
    return {
      dashboardData: {},
      orderChartData: [],
      orderTableData: [],
      dealerTableData: [],
      orderChart: ''
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    getRecentOrderData() {
      orderRecentApi({
        pageIndex: 1,
        pageNum: 5
      }).then(res => {
        this.orderTableData = res.data
      }).catch(err => {
        console.log(err)
      })
    },
    getPendingDealersData() {
      queryDealerDashboardApi({
        state: '0',
        pageIndex: 1,
        pageNum: 20
      }).then(res => {
        this.dealerTableData = res.data.records
      }).catch(err => {
        console.log(err)
      })
    },
    transformToChartData(array) {
      let xAxis = {
        xAxisTxt: [],
        xAxisData: []
      }
      var m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Spt', 'Oct', 'Nov', 'Dec']

      if (array) {
        if (array.length) {
          if (array.length > 0) {
            for (let i = 0; i < array.length; i++) {
              xAxis.xAxisTxt.push(m[array[i].month - 1] + ' ' + array[i].day)
              xAxis.xAxisData.push(array[i].orderNum)
            }
            return xAxis
          }
        }
      }
      return xAxis
    },
    loadData() {
      this.orderChart = this.$echarts.init(document.getElementById('orderChart'))
      this.orderChart.showLoading()
      switch (this.role) {
        case this.adminValue:
          adminDashboardApi().then(res => {
            this.dashboardData = res.data
            this.drawChart(this.transformToChartData(res.data.curMonthOrderNum))
            this.orderChart.hideLoading()
          }).catch(err => {
            console.log(err)
            this.orderChart.hideLoading()
          })
          this.getRecentOrderData()
          break
        case this.agencyValue:
          agentDashboardApi().then(res => {
            this.dashboardData = res.data
            this.drawChart(this.transformToChartData(res.data.curMonthOrderNum))
            this.orderChart.hideLoading()
          }).catch(err => {
            console.log(err)
            this.orderChart.hideLoading()
          })
          this.getRecentOrderData()
          this.getPendingDealersData()
          break
        case this.dealerMValue:
          masterdealerDashboardApi().then(res => {
            this.dashboardData = res.data
            this.drawChart(this.transformToChartData(res.data.curMonthOrderNum))
            this.orderChart.hideLoading()
          }).catch(err => {
            console.log(err)
            this.orderChart.hideLoading()
          })
          this.getRecentOrderData()
          this.getPendingDealersData()
          break
        case this.dealerValue:
          dealerDashboardApi().then(res => {
            this.dashboardData = res.data
            this.drawChart(this.transformToChartData(res.data.curMonthOrderNum))
            this.orderChart.hideLoading()
          }).catch(err => {
            console.log(err)
            this.orderChart.hideLoading()
          })
          this.getRecentOrderData()
          break
        default:
          this.$message.error('ERROR')
          break
      }
    }, // 得到数据表格
    handleConfirm(row) {
      if (this.role == this.dealerMValue) {
        verifyMdealerApi({ 'id': row.id }).then(res => {
          this.$message({
            message: 'Pass！',
            type: 'success'
          })
          this.loadData()
        }).catch(err => {
          console.log(err)
        })
      } else {
        passOwnerDealerApi(row).then(res => {
          this.$message({
            message: 'Pass！',
            type: 'success'
          })
          this.loadData()
        }).catch(err => {
          console.log(err)
        })
      }
    },
    handleEditView(row) {
      if (this.role == this.dealerValue) {
        this.$router.push('/My-Orders/Edit/' + row.oid)
      } else {
        this.$router.push({path: '/Orders/Edit/' + row.oid })
      }
    },
    handleEdit(row) {
      this.$setDetail(row)
      this.$router.push({ path: '/Customers/Detail' })
    },
    drawChart(xAxis) {
      const showd = xAxis.xAxisData.length && (xAxis.xAxisData.length > 0)
      this.orderChart.setOption({
        title: {
          show: !showd,
          text: 'No Data',
          left: 'center',
          top: 'center',
          textStyle: {
            color: 'pink',
            fontSize: 36,
            fontWeight: 278
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        dataZoom: [
          {
            type: 'slider',
            start: 0,
            end: 100
          },
          {
            type: 'inside',
            start: 0,
            end: 100
          }],
        xAxis: {
          type: 'category', // 还有其他的type，可以去官网喵两眼哦
          data: xAxis.xAxisTxt, // x轴数据
          name: 'Day' // x轴名称
        },
        yAxis: {
          type: 'value',
          name: 'Pesanan' // y轴名称
        },
        grid: {
          left: '3%',
          right: '6%', // 调整大小
          containLabel: true
        },
        legend: {
          orient: 'vertical',
          x: 'center',
          y: 'top',
          data: ['Purchase Order']
        },
        series: [
          {
            name: 'Pesanan',
            data: xAxis.xAxisData,
            type: 'line'
          }
        ]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .dashboard {
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }

  .head-big-title {
    text-align: left;
    font-size: 20px;
    margin: 20px 0 20px 3%;
  }

  .big-title {
    text-align: left;
    font-size: 19px;
    margin: 20px 0 20px 3%;
    clear: both;
  }

  .dashboard-container {
    margin-top: 20px;
    text-align: center;
  }

  .four-card {
    width: 24%;
    margin-right: 1%;
    margin-bottom: 16px;
    display: inline-block;
    height: 88px;
    text-align: left;
    float: left;

    .title {
      display: block;
      font-size: 15px;
      margin: 0;
    }

    .count {
      font-size: 19px;
      margin: 6px 0 0 0;
      color: #ffe140;
    }
  }

  .five-card {
    width: 19%;
    margin-right: 1%;
    margin-bottom: 16px;
    display: inline-block;
    text-align: left;
    height: 88px;
    float: left;

    .title {
      display: block;
      font-size: 15px;
      margin: 0;
    }

    .count {
      font-size: 19px;
      margin: 6px 0 0 0;
      color: #ffe140;
    }
  }

  .last-days-order {
    width: 92%;
    background-color: white;
    margin: 0 4%;
    border-radius: 20px;
  }
</style>
